package com.nativetalk.service.member.login;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberLogin;
import com.nativetalk.bean.member.TdNtMemberToken;
import com.nativetalk.bean.rongyun.RongCloudConfig;
import com.nativetalk.bean.rongyun.TokenResult;
import com.nativetalk.bean.user.TdNtUserLoginLog;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.rongCloud.RongCloud;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.MD5;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dao.TdNtMemberDao;
import com.nativetalk.dao.TdNtUserLoginLogDao;
import com.tls.tls_sigature.tls_sigature;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Reader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 15/12/24.
 */
@Service
public class MemberLoginServiceImpl implements  MemberLoginService {
    private static Logger logger = Logger.getLogger(MemberLoginServiceImpl.class);
    private static String WAIJIAOJUN_URL = "file.waijiaojun.com/";
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtUserLoginLogDao tdNtUserLoginLogDao;
    @Resource
    private RongCloudConfig rongCloudConfig;
    @Override
    @Transactional
    public RetInfo login(TdNtMemberLogin user, int version, String ip) {
        String logInfo = this.getClass().getName() + ":login:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        TokenResult tokenResult = null;
        try {
            TdNtMember tdNtMember = tdNtMemberDao.findTdNtMemberByPhone(user.getMemb_email());
            String appKey = rongCloudConfig.getAppkey();
            String appSecret = rongCloudConfig.getSecret();
            if (tdNtMember != null && tdNtMember.getMemb_password() != null) {
                TdNtUserLoginLog tdNtUserLoginLog = new TdNtUserLoginLog();
                tdNtUserLoginLog.setUser_id(tdNtMember.getMemb_id());
                tdNtUserLoginLog.setUser_type(Integer.parseInt(Constants.user_type_student));
                tdNtUserLoginLog.setYyyymm(CommonUtil.getMonth(new Date()));
                tdNtUserLoginLog.setLogin_ip(ip);
                tdNtUserLoginLog.setEqu_client_id(tdNtMember.getEqu_client_id() + "||" + user.getEqu_client_id());//设备标识
                tdNtUserLoginLog.setEqu_type(user.getEqu_type());//设备类型
                tdNtUserLoginLog.setAccount(user.getMemb_email());//登录账号
                tdNtUserLoginLog.setOld_token(tdNtMember.getToken());
                tdNtUserLoginLog.setUid(tdNtMember.getUid());

                if (tdNtMember.getMemb_password().equals(MD5.code(user.getMemb_password()))) {
                    if (tdNtMember.getMemb_islock().equals("1")) {
                        /**
                         * 更新用户token
                         */
                        TdNtMemberToken tdNtMemberToken = new TdNtMemberToken();
                        tdNtMemberToken.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMemberToken.setToken(CommonUtil.getToken());
                        tdNtMemberToken.setEqu_client_id(user.getEqu_client_id());
                        tdNtMemberToken.setEqu_type(user.getEqu_type());
                        tdNtMemberToken.setThird_token(null);
                        tdNtMemberToken.setNowLoginType(Constants.ThirdPartyType.mobile_Type);
                        tdNtMemberDao.updateTdNtMemberInfo(tdNtMemberToken);
                        /**
                         * 删除把用户对象放入memcached原有用户对象
                         */
                        MemcachedUtils.delete(tdNtMember.getToken());
                        /**
                         * 把用户对象放入memcached
                         */
                        tdNtMember.setToken(tdNtMemberToken.getToken());
                        tdNtMember.setEqu_client_id(tdNtMemberToken.getEqu_client_id());
                        tdNtMember.setEqu_type(tdNtMemberToken.getEqu_type());
                        MemcachedUtils.add(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);


                        Map<String,Object> map = new HashMap<>();

                        if(tdNtMember.getRongcloud_token() == null || tdNtMember.getRongcloud_token() == ""){
                            // 获取融云 Token 方法
                            Reader reader = null ;
                            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
                            String memb_id="student"+tdNtMember.getMemb_id();
                            String memb_head_portraituri = tdNtMember.getMemb_head_portrait();
                            if(!memb_head_portraituri.contains("http")){
                                memb_head_portraituri = WAIJIAOJUN_URL + memb_head_portraituri;
                            }
                            tokenResult = rongCloud.user.getToken(memb_id,tdNtMember.getMemb_name(),memb_head_portraituri);
                            tdNtMemberDao.updateRongCloudToken(tokenResult.token, Integer.valueOf(tdNtMember.getMemb_id()));
                            if(tokenResult.getToken()!= null && tokenResult.getToken()!=""){
                                map.put("rongCloudToken",tokenResult.getToken());
                            }
                            logger.info(tokenResult.toString());
                        }else{
                            map.put("rongCloudToken",tdNtMember.getRongcloud_token());
                        }

                        map.put("token",tdNtMemberToken.getToken());
                        if (version>=5) {
                            map.put("sig", tls_sigature.getUsersig(Constants.member + tdNtMember.getMemb_id()));
                            map.put("Identifier", Constants.member + tdNtMember.getMemb_id());

                        }
                        map.put("uid", tdNtUserLoginLog.getUid());
                        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                        retInfo.setTip(ValidationMessages.getValue("LOGIN.SUCCESS"));
                        retInfo.setObj(map);
                        tdNtUserLoginLog.setIs_success("0");
                        tdNtUserLoginLog.setLogin_failer_desc("登录成功");
                        tdNtUserLoginLog.setUid(tdNtUserLoginLog.getUid());
                    } else {
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip("账号已锁定,请联系客服");
                        tdNtUserLoginLog.setIs_success("1");
                        tdNtUserLoginLog.setLogin_failer_desc("账号锁定");
                    }

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("LOGIN.ERROR"));
                    tdNtUserLoginLog.setIs_success("1");
                    tdNtUserLoginLog.setLogin_failer_desc("密码错误");
                }
                tdNtUserLoginLogDao.insertTdNtUserLoginLog(tdNtUserLoginLog);
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("LOGIN.WRONG"));
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    @Transactional
    public RetInfo out(TdNtMember tdNtMember) {
        String logInfo = this.getClass().getName() + ":out:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMemberToken tdNtMemberToken = new TdNtMemberToken();
            tdNtMemberToken.setMemb_id(tdNtMember.getMemb_id());
            tdNtMemberToken.setToken(CommonUtil.getToken());
            tdNtMemberToken.setEqu_client_id(tdNtMember.getEqu_client_id());
            tdNtMemberToken.setEqu_type(tdNtMember.getEqu_type());

            //如果删除缓存失败，则要求用户重新退出，不能更新token
            //出现过：缓存中有token，但是数据库中没有token的情况
            MemcachedUtils.delete(tdNtMember.getToken());
            tdNtMemberDao.updateTdNtMemberToken(tdNtMemberToken);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("退出成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    public RetInfo updateEquClientId(int memb_id, String equ_client_id, String equ_type) {
        RetInfo retInfo = new RetInfo();
        if (equ_client_id == null || "".equals(equ_client_id.trim())) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("无效参数：equ_client_id不能为空");
            return retInfo;
        } else if (equ_type == null || "".equals(equ_type.trim())) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("无效参数：equ_type不能为空");
            return retInfo;
        }
        try {
            //更新数据库
            tdNtMemberDao.updateEquClientIdByMembId(memb_id, equ_client_id, equ_type);
            //更新缓存
            TdNtMember tdNtMember = tdNtMemberDao.findMember(memb_id);
            tdNtMember.setEqu_client_id(equ_client_id);
            tdNtMember.setEqu_type(equ_type);
            MemcachedUtils.replace(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("更新DeviceToken成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        return retInfo;
    }
}
